package com.wagn.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.wagn.config.exceptionHandler.MyException;
import com.wagn.eduservice.entity.EduSubject;
import com.wagn.eduservice.entity.excel.excelentity.SubjectExcelEntity;
import com.wagn.eduservice.entity.excel.excelutil.SubjectExcelListener;
import com.wagn.eduservice.entity.subject.SubjectClassifyEntity;
import com.wagn.eduservice.mapper.EduSubjectMapper;
import com.wagn.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-08-16
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        if(file.getContentType().toString().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
            try{
                InputStream inputStream = file.getInputStream();
                EasyExcel.read(inputStream, SubjectExcelEntity.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        else {
            throw new MyException(20001, "文件类型错误");
        }
    }

    @Override
    public List<SubjectClassifyEntity> getSubjectList(EduSubjectService eduSubjectService) {
        List<SubjectClassifyEntity> rs = new ArrayList<>();

        List<EduSubject> list = eduSubjectService.list(null);

        for(EduSubject eduSubject:list){
            if(eduSubject.getParentId().equals("0")){
                SubjectClassifyEntity temp = new SubjectClassifyEntity();
                temp.setId(eduSubject.getId());
                temp.setLabel(eduSubject.getTitle());
                //找出该一级分类的所有二级分类
                ArrayList<SubjectClassifyEntity> templist2 = new ArrayList<>();//新建二级列表

                for(EduSubject e2:list){
                    if(e2.getParentId().equals(eduSubject.getId())){
                        SubjectClassifyEntity temp2 = new SubjectClassifyEntity();
                        temp2.setId(e2.getId());
                        temp2.setLabel(e2.getTitle());
                        templist2.add(temp2);
                        temp.setChildren(templist2);
                    }
                }

                rs.add(temp);

            }
        }

        return rs;
    }
}
